<!--
 * @Description: 
 * @FilePath: \rs_wms_pc\src\views\storehouse\checkPlan\index.vue
-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="no" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入no"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="计划名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点方式" prop="checkWay">
        <el-select v-model="queryParams.checkWay" placeholder="请选择盘点方式">
            <el-option v-for="dict in dict.type.storehouse_check_way" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
        <!-- <el-input
          v-model="queryParams.checkWay"
          placeholder="请输入盘点方式:PRODUCT-物料;LOCATION-位置"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
      </el-form-item>
      <el-form-item label="盘点类型" prop="checkType">
          <el-select v-model="queryParams.checkType" placeholder="请选择盘点方式">
              <el-option v-for="dict in dict.type.storehouse_check_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="盘点仓库" prop="storehouseNo">
        <el-input
          v-model="queryParams.storehouseNo"
          placeholder="请输入仓库编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['storehouse:checkPlan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['storehouse:checkPlan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['storehouse:checkPlan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="handleGenerator"
          v-hasPermi="['storehouse:checkPlan:generator']"
        >手动生成盘点任务</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['storehouse:checkPlan:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkPlanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" />
      <!-- <el-table-column label="ID" align="center" prop="id" /> -->
      <!-- <el-table-column label="no" align="center" prop="no" /> -->
      <af-table-column label="计划名称" align="center" prop="name" />
      <af-table-column label="盘点类型" align="center" prop="checkType" width="80">
        <template slot-scope="scope">
            <dict-tag :options="dict.type.storehouse_check_type" :value="scope.row.checkType" />
        </template>
      </af-table-column>
      <af-table-column label="盘点方式" align="center" prop="checkWay" width="80">
        <template slot-scope="scope">
            <dict-tag :options="dict.type.storehouse_check_way" :value="scope.row.checkWay" />
        </template>
      </af-table-column>
      <af-table-column label="盘点仓库编号" align="center" prop="storehouseNo" width="120"/>
      <af-table-column label="计划开始时间" align="center" prop="startTime" width="152"/>
      <el-table-column :label="$t('createUser')" align="center" prop="createBy" width="80"/>
      <el-table-column :label="$t('createTime')" align="center" prop="createTime" width="152" />
      <el-table-column :label="$t('updateUser')" align="center" prop="updateBy" width="100" />
      <el-table-column :label="$t('updateTime')" align="center" prop="updateTime" width="160" />
          
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['storehouse:checkPlan:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['storehouse:checkPlan:remove']"
          >删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存盘点计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70vw" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :inline="true">
        <!-- <el-form-item label="no" prop="no">
          <el-input v-model="form.no" placeholder="请输入no" />
        </el-form-item> -->
        <el-form-item label="计划名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入计划名称" />
        </el-form-item>
        <el-form-item label="盘点方式" prop="checkWay">
            <el-select v-model="form.checkWay" placeholder="请选择盘点方式">
                <el-option v-for="dict in dict.type.storehouse_check_way" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          <!-- <el-input v-model="form.checkWay" placeholder="请输入盘点方式:PRODUCT-物料;LOCATION-位置" /> -->
        </el-form-item>
        <el-form-item label="盘点类型" prop="checkType">
            <el-select v-model="form.checkType" placeholder="请选择盘点类型">
                <el-option v-for="dict in dict.type.storehouse_check_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          <!-- <el-input v-model="form.checkWay" placeholder="请输入盘点方式:PRODUCT-物料;LOCATION-位置" /> -->
        </el-form-item>
        <el-form-item label="仓库编号" prop="storehouseNo">
          <el-select style="width:100%;" v-model="form.storehouseNo" filterable placeholder="请选择仓库" @change="clearDetailList">
            <el-option
              v-for="dict in storehouseList"
              :key="dict.no"
              :label="dict.no+' - '+dict.name"
              :value="dict.no"
              @click.native="form.storehouseName = dict.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="是否删除：1是 0否" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入是否删除：1是 0否" />
        </el-form-item> -->
        
        <div class="flex-row-end">
          <el-button type="primary" @click="addProduct">新 增</el-button>
        </div>
        <el-table  :data="form.stockCheckPlanDetailList">
          <el-table-column label="序号" type="index" width="50" />
          <!-- <el-table-column label="ID" align="center" prop="id" /> -->
          <!-- <el-table-column label="no" align="center" prop="no" /> -->
          <el-table-column v-if="form.checkWay == 'LOCATION'" label="仓库" align="center" prop="storehouseNo" />
          <el-table-column v-if="form.checkWay == 'LOCATION'" label="库区" align="center" prop="areaNo" />
          <el-table-column v-if="form.checkWay == 'LOCATION'" label="库位" align="center" prop="locationNo" />
          
          <el-table-column v-if="form.checkWay == 'PRODUCT'" label="物料编号" align="center" prop="productNo" />
          <el-table-column v-if="form.checkWay == 'PRODUCT'" label="物料名称" align="center" prop="productName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteDetail(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <ProductDialog ref="productSelectDialog" @selectChange="selectChange" :query="{storehouseNo: form.storehouseNo}"></ProductDialog>
    <LocationDialog ref="locationSelectDialog" @selectChange="selectChange" :query="{storehouseNo: form.storehouseNo}"></LocationDialog>

  </div>
</template>

<script>
import { listCheckPlan, getCheckPlan, delCheckPlan, addCheckPlan, addWithDetailCheckPlan, updateCheckPlan, generator, getCheckPlanDetail } from "@/api/storehouse/checkPlan";
import { listStorehouse } from "@/api/basic/storehouse";
import ProductDialog from "./productDialog.vue";
import LocationDialog from "./locationDialog.vue";

export default {
  name: "CheckPlan",
  dicts: ["storehouse_check_type","storehouse_check_way"],
  components:{ ProductDialog, LocationDialog },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存盘点计划表格数据
      checkPlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        name: null,
        checkType: null,
        checkWay: null,
        storehouseNo: null,
        startTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "计划名称不能为空", trigger: "blur" }
        ],
        checkWay: [
          { required: true, message: "盘点方式不能为空", trigger: "blur" }
        ],
        checkType: [
          { required: true, message: "盘点类型不能为空", trigger: "blur" }
        ],
        storehouseNo: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ]
      },
      storehouseList: [],
    };
  },
  created() {
    this.getList();
    this.getStorehouseList()
  },
  methods: {
    clearDetailList(){
      console.log('clearDetailList')
      this.$set(this.form,'stockCheckPlanDetailList',[])
    },
    handleDeleteDetail(index){
      this.form.stockCheckPlanDetailList.splice(index,1)
    },
    selectChange(row){
      if(!row.length) return
      row.forEach(item=>{
        let detailItem = null;
        if(this.form.checkWay == 'PRODUCT'){
          detailItem = this.form.stockCheckPlanDetailList.find(subItem=>subItem.productNo == item.productNo)
          if(!detailItem){
            this.form.stockCheckPlanDetailList.push({ planNo:this.form.no, productNo:item.productNo, productName: item.productName})
          }
        }else if(this.form.checkWay == 'LOCATION'){
          detailItem = this.form.stockCheckPlanDetailList.find(subItem=>subItem.locationNo == item.no)
          if(!detailItem){
            this.form.stockCheckPlanDetailList.push({
                planNo:this.form.no,
                storehouseNo: item.storehouseNo, 
                storehouseName: item.storehouseName, 
                areaNo: item.storehouseAreaNo, 
                areaName: item.storehouseAreaName, 
                locationNo:item.no, 
                locationName: item.name 
            })
          }
        }
      })
      console.log(this.form.stockCheckPlanDetailList)
    },
    addProduct(){
      if(!this.form.checkWay){
        this.$modal.msgError("请先选择盘点方式");
        return
      }
      if(this.form.checkWay == 'PRODUCT'){
        this.$refs.productSelectDialog.init();
        return
      }
      if(this.form.checkWay == 'LOCATION' && !this.form.storehouseNo){
        this.$modal.msgError("请先选择盘点仓库");
      }else{
        this.$refs.locationSelectDialog.init();
      }
    },
    //   手动生成盘点任务
    handleGenerator(row){
      const ids = row.id || this.ids;
      this.$modal.confirm('是否生成库存盘点任务？').then(function() {
        return generator(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("生成成功");
      }).catch(() => {});
    },
      // 获取仓库列表
      getStorehouseList(){
        listStorehouse({pageSize: 0}).then(response => {
          this.storehouseList = response.rows;
        });
      },
    /** 查询库存盘点计划列表 */
    getList() {
      this.loading = true;
      listCheckPlan(this.queryParams).then(response => {
        this.checkPlanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        no: null,
        name: null,
        checkType: null,
        checkWay: null,
        storehouseNo: null,
        startTime: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        createTime: null,
        delFlag: null,
        stockCheckPlanDetailList:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库存盘点计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCheckPlan(id).then(response => {
        this.form = response.data;
        this.title = "修改库存盘点计划";
        getCheckPlanDetail({planNo: this.form.no, pageNum:1, pageSize:0}).then(res=>{
          this.form.stockCheckPlanDetailList = res.rows;
          this.open = true;
        })
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form.stockCheckPlanDetailList)
            if(!this.form.stockCheckPlanDetailList || !this.form.stockCheckPlanDetailList.length){
                this.$modal.msgError("请选择需要盘点的物料/位置");
                return
            }
            addWithDetailCheckPlan(this.form).then(response => {
              if (this.form.id != null) {
                this.$modal.msgSuccess("修改成功");
              }else{
                this.$modal.msgSuccess("新增成功");
              }
              this.open = false;
              this.getList();
            });
          
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
        return delCheckPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('storehouse/checkPlan/export', {
        ...this.queryParams
      }, `checkPlan_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

